<?php

namespace app\api\controller;

use think\Controller;
use think\Db;

class Aipub extends Controller {
    public $password = "这里设置接口密码";
    public $titleUnique = TRUE;

    public function content() {
        $postdata = $_POST ?? [];
        if ($this->password != $postdata['password']) {
            exit('验证密码错误');
        }
        $postdata['password'] = isset($postdata['password']) ? $postdata['password'] : "";
        $postdata['title'] = isset($postdata['title']) ? $postdata['title'] : "";
        $postdata['title'] = isset($postdata['Title']) ? $postdata['Title'] : $postdata['title'];
        $postdata['keyword'] = isset($postdata['keyword']) ? $postdata['keyword'] : "";
        $postdata['description'] = isset($postdata['description']) ? $postdata['description'] : "";
        $postdata['description'] = isset($postdata['Intro']) ? $postdata['Intro'] : $postdata['description'];
        $postdata['content'] = isset($postdata['content']) ? $postdata['content'] : "";
        $postdata['content'] = isset($postdata['Content']) ? $postdata['Content'] : $postdata['content'];
        $postdata['head_pic'] = isset($postdata['head_pic']) ? $postdata['head_pic'] : "";
        $postdata['imgs'] = isset($postdata['imgs']) ? $postdata['imgs'] : "";
        $postdata['category'] = isset($postdata['category']) ? $postdata['category'] : "";
        $postdata['category_ids'] = isset($postdata['category_ids']) ? $postdata['category_ids'] : "";
        $postdata['category_ids'] = isset($postdata['CateID']) ? $postdata['CateID'] : $postdata['category_ids'];
        $postdata['status'] = isset($postdata['status']) ? $postdata['status'] : 1;
        $postdata['pubdate'] = isset($postdata['pubdate']) ? $postdata['pubdate'] : 1;
        $postdata['channelid'] = isset($postdata['channelid']) ? $postdata['channelid'] : "1";
        $postdata['author'] = isset($postdata['author']) ? $postdata['author'] : "";
        if (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on") {
            $http = "https://";
        } else {
            $http = "http://";
        }
        $domain = $http . str_replace('\\', '/', $_SERVER['HTTP_HOST']);
        //检查标题
        $title = isset($postdata['title']) ? addslashes($postdata['title']) : '';//标题
        if (empty($title)) {
            $this->aipub_failRsp(1404, "title is empty", "标题不能为空");
        }
        //检查内容
        $content = isset($postdata['content']) ? $postdata['content'] : '';
        if (empty($content)) {
            $this->aipub_failRsp(1404, "content is empty", "内容不能为空");
        }
        //检查栏目
        $typeid = isset($postdata['category_ids']) ? addslashes($postdata['category_ids']) : '';
        if (empty($typeid)) {
            $this->aipub_failRsp(1404, "typeid is empty", "栏目ID不能为空");
        }
        //检查频道模型
        $channel = isset($postdata['channelid']) ? addslashes($postdata['channelid']) : '';
        if (empty($channel)) {
            $this->aipub_failRsp(1404, "channel is empty", "频道模型不能为空");
        }
        //        if (self::$titleUnique) {
        //            $archivesList = Db::name('archives')->where('title', $title)->select();
        //            $existAid = $archivesList[0]['aid'];
        //            if ($existAid > 0) {
        //                return $this->keydatas_successRsp(array("url" => $domain . "/index.php?m=home&c=View&a=index&aid=" . $existAid), '标题已存在');
        //            }
        //        }
        $seo_keywords = $postdata['keyword'];
        if (!empty($seo_keywords)) {
            $seo_keywords = str_replace('，', ',', $seo_keywords);
        }
        //提取文章内容中第一张图片作为封面
        //调整成简数的方法
        //$litpic = get_html_first_imgurl($content) ?: '';
        $litpic = $this->getThumb($postdata);
        //是否有封面图
        if (empty($litpic)) {
            $is_litpic = 0; // 无封面图
        } else {
            $is_litpic = 1; // 有封面图
        }
        // SEO描述
        $seo_description = '';
        if (empty($postdata['description']) && !empty($content)) {
            $seo_description = @msubstr(checkStrHtml($content), 0, config('global.arc_seo_description_length'), FALSE);
        } else {
            $seo_description = $postdata['description'];
        }
        if (!empty($postdata['pubdate'])) {
            $add_time = $postdata['pubdate'];
        } else {
            $add_time = time();
        }
        $content = $this->replaceimg($content);
        $content = htmlspecialchars($content);

        // --存储数据
        $newData = array(
            'typeid'          => $typeid,
            'channel'         => $channel,
            'is_b'            => empty($postdata['is_b']) ? 0 : $postdata['is_b'],
            'title'           => $title,
            'litpic'          => $litpic,
            'is_head'         => empty($postdata['is_head']) ? 0 : $postdata['is_head'],//头条（0=否，1=是）
            'is_special'      => empty($postdata['is_special']) ? 0 : $postdata['is_special'],//特荐（0=否，1=是）
            'is_top'          => empty($postdata['is_top']) ? 0 : $postdata['is_top'],//置顶（0=否，1=是）
            'is_recom'        => empty($postdata['is_recom']) ? 0 : $postdata['is_recom'],//推荐（0=否，1=是）
            'is_litpic'       => $is_litpic,
            'author'          => $postdata['author'],
            'click'           => mt_rand(100, 300),
            'arcrank'         => empty($postdata['status']) ? -1 : 0,//阅读权限：0=开放浏览，-1=待审核稿件
            'seo_title'       => $postdata['title'],
            'seo_keywords'    => $seo_keywords,
            'seo_description' => $seo_description,
            'tempview'        => 'view_article.htm',
            'status'          => 1,
            'admin_id'        => 1,
            'lang'            => $this->admin_lang,
            'sort_order'      => 100,
            'add_time'        => $add_time,
            'update_time'     => $add_time,
            'content'         => $content,
            'addonFieldExt'   => ['content' => $content],
            'tags'            => $postdata['tags'],
        );
        $aid = M('archives')->insertGetId($newData);
        # $aid = Db::name('archives')->insertGetId($newData);
        if ($aid) {
            Db::name('article_pay')->insert([
                'aid'          => $aid,
                'part_free'    => $content,
                'size'         => 1,
                'free_content' => $content,
                'add_time'     => $add_time,
            ]);
            #model('Article')->afterSave($aid, $newData, 'add');
            //添加文章内容
            $this->afterSave($aid, $newData, 'add');
            $docFinalUrl = $domain . '/index.php?m=home&c=View&a=index&aid=' . $aid;
            /////图片http下载，不能用_POST
            $this->downloadImages($postdata);
            $this->aipub_successRsp(array("url" => $docFinalUrl));
        } else {
            $this->aipub_failRsp(1403, "insert archives,article_content error", "文章发布错误");
        }
    }

    /**
     * 后置操作方法
     * 自定义的一个函数 用于数据保存后做的相应处理操作, 使用时手动调用
     * @param int $aid 产品id
     * @param        $data
     * @param string $opt 操作
     * @return void
     */
    private function afterSave($aid, $data, $opt) {
        //写入文章内容
        Db::name('article_content')->data(array(
            'aid'         => $aid,
            'content'     => $data['content'],
            'add_time'    => $data['add_time'],
            'update_time' => $data['update_time'],
        ))->insert();
        Db::name('article_pay')->insert([
            'aid'          => $aid,
            'part_free'    => $data['content'],
            'size'         => 1,
            'free_content' => $data['content'],
            'add_time'     => $data['add_time'],
        ]);
        // --处理TAG标签
        model('Taglist')->savetags($aid, $data['typeid'], $data['tags']);
    }

    /**
     * 获取文件完整路径
     * @return string
     */
    private function getFilePath() {
        //$rootUrl=$this->options->siteUrl();
        //使用php的方法试试
        ///uploads/ueditor/20200620/1-20062010343IR.jpeg
        $rootUrl = dirname(dirname(dirname(dirname(__FILE__))));
        return $rootUrl . '/uploads/ueditor';
    }

    /**
     * 查找文件夹，如不存在就创建并授权
     * @return string
     */
    private function createFolders($dir) {
        return is_dir($dir) or ($this->createFolders(dirname($dir)) and mkdir($dir, 0777));
    }

    //取得文章正文内容的第一张图片做为缩略图
    private function getThumb($post) {
        $xstr = isset($post['content']) ? $post['content'] : '';
        //匹配图片的src
        $pattern = '/<img .*?src=[\"|\']+(.*?)[\"|\']+.*?>/';
        preg_match_all($pattern, $xstr, $match);
        $imgurl = $match[1][0];
        $img = $this->saveImages($imgurl);
        return $img;
    }

    /**
     * 获取替换文章中的图片路径
     * @param string $xstr 内容
     * @param string $keyword 创建照片的文件名
     * @param string $oriweb 网址
     * @return string
     *
     */
    function replaceimg($xstr) {
        //匹配图片的src
        $pattern = '/<img .*?src=[\"|\']+(.*?)[\"|\']+.*?>/';
        preg_match_all($pattern, $xstr, $match);
        foreach ($match[1] as $imgurl) {
            $img = $this->saveImages($imgurl);
            if (!empty($img)) {
                $xstr = str_replace($imgurl, $img, $xstr);
            }
        }
        return $xstr;
    }

    ////图片http下载
    private function downloadImages($post) {
        try {
            $downloadFlag = isset($post['__aii_download_imgs_flag']) ? $post['__aii_download_imgs_flag'] : '';
            if (!empty($downloadFlag) && $downloadFlag == "true") {
                $docImgsStr = isset($post['__aii_docImgs']) ? $post['__aii_docImgs'] : '';
                if (!empty($docImgsStr)) {
                    $this->saveImages($docImgsStr);
                }
            }
        } catch (Exception $ex) {
            //error_log('error:'.$e->
        }
    }

    /****将网络图片保存到本地***/
    private function saveImages($docImgsStr) {
        $docImgs = explode(',', $docImgsStr);
        $file = '';
        $returnfile = '';
        if (is_array($docImgs)) {
            $uploadDir = $this->getFilePath();
            $d = date('Ymd', time());
            foreach ($docImgs as $imgUrl) {
                $urlItemArr = explode('/', $imgUrl);
                $itemLen = count($urlItemArr);
                $imgName = $urlItemArr[$itemLen - 1];
                $finalPath = $uploadDir . '/' . $d;
                if ($this->createFolders($finalPath)) {
                    $file = $finalPath . '/' . time() . "-" . $imgName;
                    $returnfile = '/uploads/ueditor/' . $d . '/' . time() . "-" . $imgName;
                    if (!file_exists($file)) {
                        $doc_image_data = file_get_contents($imgUrl);
                        file_put_contents($file, $doc_image_data);
                    }
                }
            }
        }
        return $returnfile;
    }

    /**
     *获取网站栏目
     **/
    public function aipubArctypelist() {
        $arctypeList = Db::name('arctype')->where('lang', 'cn')->select();
        foreach ($arctypeList as $rec) {
            $cates[] = array('cid' => $rec['id'], 'pid' => $rec['parent_id'], 'ctype' => $rec['current_channel'], 'cname' => $rec['typename']);
        }
        echo "<select name='list'>";
        echo $this->maketreeArc($cates, 0, '');
        echo '</select>';
    }

    /***生成目录的一个遍历算法***/
    public function maketreeArc($ar, $id, $pre) {
        $ids = '';
        foreach ($ar as $k => $v) {
            $pid = $v['pid'];
            $cname = $v['cname'];
            $cid = $v['cid'];
            $ctype = $v['ctype'];
            if ($pid == $id) {
                $ids .= "<option value='$cid" . "__" . "$ctype'>{$pre}{$cname}</option>";
                foreach ($ar as $kk => $vv) {
                    $pp = $vv['pid'];
                    if ($pp == $cid) {
                        $ids .= $this->maketreeArc($ar, $cid, $pre . "&nbsp;&nbsp;");
                        break;
                    }
                }
            }
        }
        return $ids;
    }

    private function aipub_mergeRequest() {
        if (isset($_GET['__aii_flag'])) {
            $postdata = array_merge($_GET, $_POST);
        } else {
            $postdata = $_POST;
        }
        return $postdata;
    }

    private function aipub_successRsp($data = "", $msg = "") {
        $this->aipub_rsp(1, 0, $data, $msg);
    }

    private function aipub_failRsp($code = 0, $data = "", $msg = "") {
        $this->aipub_rsp(0, $code, $data, $msg);
    }

    private function aipub_rsp($result = 1, $code = 0, $data = "", $msg = "") {
        die(json_encode(array("rs" => $result, "code" => $code, "data" => $data, "msg" => urlencode($msg))));
    }
}